package net.akkz.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FilterWithPriority implements Filter
{
	private String errorPage;
	
	@Override
	public void destroy()
	{
		// TODO Auto-generated method stub
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filter) throws IOException, ServletException
	{
		try
		{
			String path = ((HttpServletRequest) request).getServletPath();
			
			int dollIndex = path.lastIndexOf('.');
			
			
			
			if(dollIndex != -1)
			{
				String permission = path.substring(dollIndex + 1);
				String cPermission =  (String) ((HttpServletRequest) request).getSession().getAttribute("permission");

				if(!cPermission.contains(permission))
				{
					((HttpServletResponse)response).sendRedirect(((HttpServletRequest) request).getContextPath() + errorPage);
					
					return;
				}
			}

			filter.doFilter(request, response);
		}
		catch (StringIndexOutOfBoundsException e)
		{
			e.printStackTrace();
			
			throw new ServletException(e);
		}
	}

	@Override
	public void init(FilterConfig filter) throws ServletException
	{
		this.errorPage = (String)filter.getInitParameter("errorPage");
		
		if(this.errorPage == null)
			throw new ServletException("error page is not setted.");
	}
}
